from django_redis import get_redis_connection
from rest_framework import serializers

from goods import constants
from goods.models import SKU


class HotGoodsSerializer(serializers.ModelSerializer):

    class Meta:
        model =SKU
        fields = ('id', 'name', 'price', 'default_image_url','comments')




class UserHistorySerializer(serializers.Serializer):
    sku_id=serializers.IntegerField(min_value=1)
    # 数据校验
    def validate_sku_id(self,value):
        try:
            SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('没有这么个东西')
        # print('校验数据完成')
        return value

    # 保存到redis
    def create(self, validated_data):
        redis_conect=get_redis_connection('history')
        user_id=self.context['request'].user.id
        sku_id=validated_data['sku_id']
        '''lrem(name, count, value)'''
        redis_conect.lrem('history_%s' % user_id,0,sku_id)
        # 存
        '''lpush(name, *values)'''
        redis_conect.lpush('history_%s' % user_id,sku_id)
        # 剪除
        '''lrange(name, start, end)'''
        redis_conect.lrange('history_%s' % user_id,0,constants.REDSI_RETURN_NUM-1)
        # print('保存数据完成')
        return validated_data


